package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SystemUserService systemUserService ;

    @Autowired
    private RedisTemplate<String,String> redisTemplate ;
    // 检查一下redis的配置文件（我们的配置文件之前存放在： /usr/local/redis/redis.conf)
    // 1. 后台登录 daemonize=yes
    // 2. 保护模式 protected-mode=no
    // 3. 允许其他机器登录  bind: 127.... 注释掉

    @Override
    public CaptchaVo getCaptcha() {
        //生成验证码对象：宽、高、字符数量
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
        captcha.setCharType(Captcha.TYPE_ONLY_CHAR); // 验证码由纯字符组成

        //1.生成验证码和验证码图片
        String code = captcha.text();       // 获取到验证码
        String image = captcha.toBase64();  // 获取到验证码图片

        String key = RedisConstant.ADMIN_LOGIN_PREFIX+ UUID.randomUUID() ;

        //2.将验证码保存到redis中
        redisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS) ;

        //3.将验证码图片响应给前端
        return new CaptchaVo(image, key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //第一步： 对验证码做校验
        String captchaCodeFromClient = loginVo.getCaptchaCode();
        //如果客户端未发送验证码则直接抛异常
        if(!StringUtils.hasLength(captchaCodeFromClient)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //如果客户端发送过来的验证码和redis中的不一致，则抛异常
        String captchaKey = loginVo.getCaptchaKey();
        String captchaCodeFromRedis = redisTemplate.opsForValue().get(captchaKey);
        if(!StringUtils.hasLength(captchaCodeFromRedis) ){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if(!captchaCodeFromClient.equalsIgnoreCase(captchaCodeFromRedis)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //第二步： 对账号和密码做校验
        // 根据账号从数据库查询数据
        String username = loginVo.getUsername();
        SystemUser systemUserFromDB = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, username));
        if(systemUserFromDB==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        if(systemUserFromDB.getStatus()== BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        if(!systemUserFromDB.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //第三部： 经过前两步都没有抛出异常，说明登录成功了，则应该创建token
        return JwtUtil.createToken(systemUserFromDB.getId(), username) ;
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5Hex("123456"));
    }
}
